package me.yricky.alia.ui.layoutPage

import kotlinx.coroutines.flow.MutableStateFlow
import me.yricky.alia.data.hierarchy.Cell
import me.yricky.alia.data.hierarchy.Library
import me.yricky.alia.ui.Wrapper

/**
 * @author Yricky
 * @date 2022/1/30
 */
class LayoutPageViewModel {
    class ViewState(
        val lib: MutableStateFlow<Library?> = MutableStateFlow(null),
        val cellNameFilter:MutableStateFlow<String> = MutableStateFlow(""),
        val currCell: MutableStateFlow<Cell?> = MutableStateFlow(null),
        val canvasSessions:MutableStateFlow<Wrapper<MutableMap<Cell,CellCanvasViewModel>>> = MutableStateFlow(Wrapper(LinkedHashMap())),
        val dialog:MutableStateFlow<DialogInst?> = MutableStateFlow(null)
    )
    val viewState = ViewState()

    fun loadLib(lib: Library){
        val myLib = lib.copy(cells = lib.cells.sortedBy { it.name })
        viewState.lib.value = myLib
        setCell(myLib.cells.firstOrNull())

    }

    fun setCell(cell: Cell?) {
        val lib = viewState.lib.value?:return
        cell?.let { c ->
            viewState.currCell.value = c
            viewState.canvasSessions.value = viewState.canvasSessions.value.let {
                if (!it.value.contains(cell)) {
                    it.value[cell] = CellCanvasViewModel().apply { setCell(c,lib) }
                    it.update()
                } else {
                    it
                }
            }
        }
    }

    fun setCellNameFilter(string: String){
        viewState.cellNameFilter.value = string
    }

    fun closeSession(cell:Cell?){
        cell?.let{
            val sessions = viewState.canvasSessions.value.value
            if(sessions.size != 1 && sessions.contains(it)){
                sessions.remove(it)
            }
            viewState.currCell.value = sessions.keys.last()
            viewState.canvasSessions.value = Wrapper(sessions)
        }
    }

    fun setDialog(dialogInst: DialogInst?){
        viewState.dialog.value = dialogInst
    }



}